﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

/*
 * $Author: ammar $
 * 
 * $Date: 2012-03-09 20:55:05 +0100 (vr, 09 mrt 2012) $
 * $LastChangedBy: ammar $
 * $LastChangedRevision: 88 $
 */

namespace TLD_Vision.filters
{
	// Some kind of dilation filter
	// Searches for light pixels, make them dark if there is a dark pixel in the neighborhood
	public class Dilation : VisionAlgorithm
	{
		// Kernel size
		private int size = 3;

		public Dilation() : base("Dilation Filter") { }

		public override Image DoAlgorithm(Image sourceImage)
		{
			Image newImage = new Image(new Bitmap(sourceImage.Width, sourceImage.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb));

			int radius = size >> 1;

			unsafe
			{
				uint* pSrc = (uint*)sourceImage.GetDataPointer();
				uint* pNew = (uint*)newImage.GetDataPointer();

				uint pixel;
				bool b = true;

				for(int py = radius; py < sourceImage.Height - radius; py++)
				{
					for(int px = radius; px < sourceImage.Width - radius; px++)
					{
						pixel = pSrc[py * sourceImage.Width + px] & 0x00FFFFFF;

						pNew[py * sourceImage.Width + px] = 0xFFFFFFFF;

						if(pixel < 0x050505)
						{
							pNew[py * sourceImage.Width + px] = 0xFF000000;
						}
						else
						{
							b = true;

							// Find a dark pixel in the neighborhood, if found make current pixel dark too
							// and continue with next pixel
							for(int ky = -radius; ky <= radius && b == true; ky++)
							{
								for(int kx = -radius; kx <= radius && b == true; kx++)
								{
									pixel = pSrc[(py + ky) * sourceImage.Width + px + kx] & 0x00FFFFFF;
									if(pixel < 0x050505)
									{
										pNew[py * sourceImage.Width + px] = 0xFF000000;

										b = false;
									}
								}
							}
						}
					}
				}
			}

			sourceImage.Unlock();
			newImage.Unlock();

			return newImage;
		}
	}
}
